<template>
  <div class="recommend" @scroll="scrollTop()" ref="recommend">
    <header :class="{topHead:isTopHead}">
      <div class="left" @click="back()">
        <i></i>
      </div>
      <div class="center" v-show="isCenter">每日推荐</div>
    </header>
    <main>
      <div class="time">
        <div class="left">
          <span class="day">{{day}}</span>
          <span class="month">/{{month<10?'0'+month:month}}</span>
        </div>
      </div>
      <div class="list" v-show="isRecData">
        <div :class="{header:true,fixed:isFixed}">
          <div class="left hov" @click="playAll()">
            <i></i>
            <span>播放全部</span>
          </div>
          <div class="right">
            <i></i>
            <span>多选</span>
          </div>
        </div>
        <ul :class="{mt:isMt}" v-show="available_flag">
          <li
            v-for="(item,index) in recommend_data.recommend"
            :key="index"
            :class="item.available?'':'unavailable'"
          >
            <div class="img" @click="song(item.id)">
              <img v-lazy="item.album.picUrl" alt />
            </div>
            <div class="info" @click="song(item.id)">
              <p class="name">{{item.name}}</p>
              <div>
                <span class="artists" v-for="(item2,index2) in item.artists" :key="index2">
                  {{item2.name}}
                  <span v-if="index2<item.artists.length-1">/</span>
                </span>
                <span>-</span>
                <span class="album">{{item.album.name}}</span>
              </div>
            </div>
            <div class="ico">
              <i class="play" v-show="item.mvid"></i>
              <i class="more" @click.self="more(item.id,item.name)"></i>
            </div>
          </li>
        </ul>
      </div>
      <div class="empty" v-show="!isRecData">
        <img src="../images/b_5.png" alt />
      </div>
    </main>
    <!-- 点击更多按钮出现底部详情栏 -->
    <VSongDetailMore
      v-if="isSongDetailMore"
      :songId="songId"
      @songDatailClose="songDatailClose"
      @showUserPlaylist="showUserPlaylist"
      @artistsId="artistsId"
    ></VSongDetailMore>
    <!-- 用户歌单 -->
    <vUserPlaylist
      v-if="isUserPlaylist"
      :songId="songId"
      @colseUserPlaylist="colseUserPlaylist"
      @showNewPlaylist="showNewPlaylist"
      @userTracksFail="tracksFail"
      @userTracksSuccess="tracksSuccess"
    ></vUserPlaylist>
    <!-- 新建歌单 -->
    <vNewPlaylist
      v-if="isNewPlaylist"
      @colseNewPlaylist="colseNewPlaylist"
      :name="songName"
      :songId="songId"
      @colseUserPlaylist="colseUserPlaylist"
      @tracksSuccess="tracksSuccess"
    ></vNewPlaylist>
    <!-- 底部灰色提示 -->
    <vBottomGrayPrompt :prompt_msg="bottomGrayPromptMsg" v-show="isBottomGrayPrompt"></vBottomGrayPrompt>
    <!-- 多个歌手名弹窗 -->
    <vArtistNamePopup
      v-show="isArtistNamePopup"
      :artistsIdList="artistsIdList"
      @colseArtistNamePopup="colseArtistNamePopup"
    ></vArtistNamePopup>

    <v-foot-nav></v-foot-nav>
    <v-song-check-pop v-show="!song_check_data.success" :message="song_check_data.message"></v-song-check-pop>
  </div>
</template>
<script>
import { mapState } from "vuex";
import vFootNav from "@/components/foot_nav";
import vSongCheckPop from "../components/song_check_pop";
import VSongDetailMore from "@/components/song_detail_more";
import vUserPlaylist from "@/components/user_playlist";
import vNewPlaylist from "@/components/new_playlist";
import vBottomGrayPrompt from "@/components/bottom_gray_prompt";
import vArtistNamePopup from "@/components/artist_name_popup";
export default {
  components: {
    vFootNav,
    vSongCheckPop,
    VSongDetailMore,
    vUserPlaylist,
    vNewPlaylist,
    vBottomGrayPrompt,
    vArtistNamePopup
  },
  data() {
    return {
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
      isFixed: false,
      isTopHead: false,
      isMt: false,
      isCenter: false,
      music: document.getElementById("audio"),
      isSongDetailMore: false, // 控制更多详情栏显隐
      isUserPlaylist: false, // 控制用户歌单显隐
      isNewPlaylist: false, // 控制新建歌单弹窗显隐
      bottomGrayPromptMsg: "", // 底部提示信息
      isBottomGrayPrompt: false, //是否显示底部提示
      isArtistNamePopup: false, // 是否显示多个歌手名选择弹窗
      artistsIdList: [], // 歌手id
      songId: null, // 歌曲id
      songName: "" // 歌曲名
    };
  },
  computed: {
    ...mapState("recommend", [
      "recommend_data",
      "isRecData",
      "available_data",
      "available_flag"
    ]),
    ...mapState("song_check", ["song_check_data"])
  },
  created() {
    this.$store.commit("song_check/setSongCheckData", {
      success: true,
      message: "歌曲加载中。。。"
    });
    this.refresh();
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.scrollTop();
    });
  },
  beforeRouteLeave(to, from, next) {
    this.$refs.recommend.scrollTop = 0;

    next();
  },
  methods: {
    // 关闭多个歌手名弹窗
    colseArtistNamePopup() {
      this.isArtistNamePopup = false;
      this.artistsIdList = [];
    },
    // 获取多个歌手id
    artistsId({ idList }) {
      for (let i = 0; i < idList.length; i++) {
        let element = idList[i];
        this.$store
          .dispatch("artists/getArtists", { id: element })
          .then(data => {
            this.artistsIdList.push(data);
          });
      }
      this.isSongDetailMore = false;
      this.isArtistNamePopup = true;
    },
    // 收藏歌曲失败
    tracksFail() {
      this.bottomGrayPromptMsg = "歌曲已存在";
      this.isBottomGrayPrompt = true;
      setTimeout(() => {
        this.isBottomGrayPrompt = false;
        this.bottomGrayPromptMsg = "";
      }, 3000);
    },
    // 收藏歌曲成功
    tracksSuccess() {
      this.bottomGrayPromptMsg = "已收藏到歌单";
      this.isBottomGrayPrompt = true;
      setTimeout(() => {
        this.isBottomGrayPrompt = false;
        this.bottomGrayPromptMsg = "";
      }, 3000);
    },
    //控制新建歌单弹窗显示
    showNewPlaylist() {
      this.isNewPlaylist = true;
    },
    // 控制新建歌单弹窗隐藏
    colseNewPlaylist() {
      this.isNewPlaylist = false;
    },
    // 控制用户歌单显示
    showUserPlaylist() {
      this.isUserPlaylist = true;
    },
    // 控制用户歌单隐藏
    colseUserPlaylist() {
      this.isUserPlaylist = false;
    },
    // 底部详情栏关闭
    songDatailClose() {
      this.isSongDetailMore = false;
    },
    // 点击更多按钮弹出底部详情栏
    more(id, name) {
      this.songId = id;
      this.songName = name;
      this.isSongDetailMore = true;
    },
    localStorage(list, judge) {
      if (!(list instanceof Array)) {
        list = [list];
      }
      // judge为true  播放全部 把localStorage.song_list_id全部替换掉
      // judge为false 添加播放 向localStorage.song_list_id后面添加数据
      if (judge) {
        localStorage.song_list_id = JSON.stringify(list);
      } else {
        if (localStorage.song_list_id) {
          let json_list = JSON.parse(localStorage.song_list_id);
          for (let i in list) {
            if (list.hasOwnProperty(i)) {
              let element = list[i];
              let flag = false;
              json_list.forEach(item => {
                if (item.id == element.id) {
                  flag = true;
                }
              });
              if (!flag) {
                json_list.push(element);
              }
            }
          }
          localStorage.song_list_id = JSON.stringify(json_list);
        } else {
          localStorage.song_list_id = JSON.stringify(list);
        }
      }
      let obj = JSON.parse(localStorage.song_list_id);
      let c_list = [];
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          let element = obj[key];
          c_list.push(element.id);
        }
      }
      this.$store.dispatch("song_detail/getSongsDetailData", {
        ids: c_list.join(",")
      });
    },
    object(id) {
      let object = {};
      object.name = this.$route.name;
      object.id = id;
      return object;
    },
    playAll() {
      let list = [];
      let arr = this.available_data;
      for (let i in arr) {
        if (arr.hasOwnProperty(i)) {
          let element = arr[i];
          list.push(this.object(element));
        }
      }
      this.localStorage(list, true);
      this.$store
        .dispatch("song_detail/getSongDetailData", {
          ids: list[0].id
        })
        .then(data => {
          this.$store
            .dispatch("song_url/getSongUrlData", {
              id: list[0].id,
              br: "999000"
            })
            .then(data => {
              localStorage.songIsPlayId = list[0].id;
              if (!this.music.src) {
                this.music.src = data.data[0].url;
              } else {
                if (this.music.src == data.data[0].url) {
                } else {
                  this.music.src = data.data[0].url;
                }
              }
              if (this.music.paused) {
                let playPromise = this.music.play();
                if (playPromise !== undefined) {
                  playPromise
                    .then(_ => {
                      this.music.play();
                      this.$store.commit("song_status/setPlayPause", true);
                    })
                    .catch(error => {});
                }
              } else {
                this.music.pause();
                this.$store.commit("song_status/setPlayPause", false);
              }
            });
        });
    },
    song(id) {
      this.$store
        .dispatch("song_check/getSongCheckData", { id: id })
        .then(value => {
          if (value) {
            this.$refs.recommend.scrollTop = 0;
            let list = [];
            list.push(this.object(id));
            this.localStorage(list, false);
            localStorage.songIsPlayId = id;
            this.$router.push({
              path: "/song_detail",
              query: { ids: id }
            });
          }
        });
    },
    scrollTop() {
      if (this.$refs.recommend.scrollTop > 78) {
        this.isFixed = true;
        this.isTopHead = true;
        this.isMt = true;
        this.isCenter = true;
      } else if (this.$refs.recommend.scrollTop <= 78) {
        this.isFixed = false;
        this.isTopHead = false;
        this.isMt = false;
        this.isCenter = false;
      }
    },
    back() {
      this.$refs.recommend.scrollTop = 0;
      this.$router.go(-1);
    },
    refresh() {
      this.$store.dispatch("login_refresh/getLoginRefreshData", {}).then(
        data => {
          this.$store.dispatch("login_status/getLoginStatusData", {}).then(
            data => {
              this.$store.dispatch("recommend/getRecommendDate", {});
            },
            data => {
              this.$router.push({ name: "LoginSelect" });
            }
          );
        },
        data => {
          this.$router.push({ name: "LoginSelect" });
        }
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.recommend {
  width: 100%;
  height: 100%;
  overflow-y: auto;

  main {
    .time {
      padding: 0.8rem 0.3rem 0.8rem;
      background: url(../images/axy.jpg) no-repeat center;
      // background-color: rgba($color: #ff2d0f, $alpha: 0.8);
      overflow: hidden;
      .left {
        padding-top: 0.3rem;
        padding-bottom: 0.3rem;
        float: left;
        .day {
          color: #fff;
          font-size: 0.8rem;
        }
        .month {
          color: #fff;
          font-size: 0.4rem;
        }
      }
    }
    .empty {
      img {
        width: 4rem;
        margin: auto;
        margin-top: 2rem;
      }
    }
    .list {
      padding-bottom: 1rem;
      margin-top: -0.8rem;
      background-color: #fff;
      border-top-right-radius: 0.5rem;
      border-top-left-radius: 0.5rem;
      .fixed {
        position: fixed;
        top: 0.8rem;
        left: 0;
        z-index: 1000;
      }
      .header {
        box-sizing: border-box;
        background-color: #fff;
        border-top-right-radius: 0.5rem;
        border-top-left-radius: 0.5rem;
        width: 100%;
        padding: 0.2rem 0.2rem;
        overflow: hidden;
        .hov {
          position: relative;
        }

        .hov:focus {
          outline: none;
        }

        .hov:after {
          width: 140%;
          height: 0.9rem;
          content: "";
          display: block;
          position: absolute;
          top: -0.2rem;
          left: -0.2rem;
          pointer-events: none;
          background-color: #666;
          background-repeat: no-repeat;
          background-position: 50%;
          opacity: 0;
          transition: all 0.5s;
          border-top-left-radius: 0.5rem;
        }

        .hov:active:after {
          opacity: 0.3;
          transition: 0s;
        }
        .left {
          float: left;
          span {
            margin-left: 0.1rem;
            font-size: 0.38rem;
            color: #333;
            vertical-align: middle;
          }
          i {
            vertical-align: middle;
            width: 0.5rem;
            height: 0.5rem;
            display: inline-block;
            background: url(../images/bgs.png) no-repeat;
            background-size: 100% 100%;
          }
        }
        .right {
          float: right;
          span {
            margin-left: 0.1rem;
            font-size: 0.32rem;
            color: #555;
            vertical-align: middle;
          }
          i {
            vertical-align: middle;
            width: 0.5rem;
            height: 0.5rem;
            display: inline-block;
            background: url(../images/cdz.png) no-repeat;
            background-size: 100% 100%;
          }
        }
      }
      .mt {
        margin-top: 1rem;
      }
      ul {
        li.unavailable {
          opacity: 0.3;
        }
        li {
          padding: 0.2rem 0.3rem;
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          justify-content: flex-start;
          .ico {
            line-height: 0.96rem;
            .play {
              width: 0.5rem;
              height: 0.5rem;
              display: inline-block;
              vertical-align: middle;
              background: url(../images/bfz.png) no-repeat;
              background-size: 100% 100%;
            }
            .more {
              margin-left: 0.2rem;
              width: 0.36rem;
              height: 0.36rem;
              display: inline-block;
              vertical-align: middle;
              background: url(../images/b2a.png) no-repeat;
              background-size: 100% 100%;
            }
          }
          .img {
            img {
              width: 1rem;
              height: 1rem;
              border-radius: 0.1rem;
            }
          }
          .info {
            width: 3rem;
            flex: 1;
            text-align: left;
            padding-left: 0.2rem;
            p.name {
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            p {
              font-size: 0.34rem;
              color: #333;
              font-weight: 900;
              line-height: 0.6rem;
            }
            div {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              font-size: 0.24rem;
              color: #555;
            }
          }
        }
      }
    }
  }
  .topHead {
    background: url(../images/axy.jpg) no-repeat center;
    // background-color: rgba($color: #ff2d0f, $alpha: 1);
    height: 1.5rem;
  }
  header {
    width: 100%;
    height: 0.8rem;
    line-height: 0.8rem;
    left: 0rem;
    top: 0rem;
    z-index: 100;
    background-color: transparent;
    overflow: hidden;
    position: fixed;
    transition: 0.5s;
    .left {
      position: absolute;
      top: 0.1rem;
      left: 0.2rem;
      height: 0.6rem;
      i {
        background: url(../images/back.png) no-repeat;
        background-size: 100% 100%;
        width: 0.6rem;
        height: 0.6rem;
        display: inline-block;
      }
    }
    .center {
      font-size: 0.4rem;
      color: #fff;
      text-align: left;
      padding-left: 1.2rem;
      line-height: 0.9rem;
      font-weight: normal;
    }
  }
}
</style>